FIFO Queues In .NET
1 min readRapid overview
FIFO Queues in JavaScript
FIFO queues process items in the order they were added.
Simple queue
const queue: string[] = [];
queue.push('a');
queue.push('b');
const first = queue.shift();
Efficient queue
For large queues, avoid shift (O(n)). Use a pointer.
class Queue<T> {
private items: T[] = [];
private head = 0;
enqueue(item: T) { this.items.push(item); }
dequeue(): T | undefined {
if (this.head >= this.items.length) return undefined;
const item = this.items[this.head];
this.head += 1;
return item;
}
}
Interview prompt
- Why is
shift()slow for large arrays, and how do you avoid it?